package controller

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/alipay"
	"github.com/go-pay/xlog"
	"net/http"
	"zk1-project/pkg/config"
)

func AliPayNotify(c *gin.Context) {
	tradeStatus := c.PostForm("trade_status")
	fmt.Println("-------------->Notify,request:", c.Request)
	ordernum := c.PostForm("out_trade_no")
	fmt.Println("学生报名----->" + ordernum)
	fmt.Println("--------->>>", tradeStatus)
	if tradeStatus == "TRADE_CLOSED" {
		c.JSON(http.StatusOK, gin.H{
			"msg": "交易已关闭",
		})
	}
	if tradeStatus == "TRADE_SUCCESS" {
		//验签
		fmt.Println("================================")
		c.JSON(http.StatusOK, gin.H{
			"msg": "成功",
		})
	}
}
func AliPayReturn(c *gin.Context) {
	notifyReq, err := alipay.ParseNotifyToBodyMap(c.Request)
	if err != nil {
		xlog.Error(err)
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "参数错误",
		})
		return
	}
	ok, err := alipay.VerifySign(config.AliPublicKey, notifyReq)
	if err != nil {
		xlog.Error(err)
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "ok报名成功",
		})
		return
	}
	msg := ""
	if ok {
		msg = "验签成功"

	} else {
		msg = "验签失败"
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": msg,
	})
}

// 获取支付url
func AddOrder(c *gin.Context) {
	//1.获取url进行支付
	client, err := alipay.NewClient(config.AppId, config.PrivateKey, config.IsProduction)
	if err != nil {
		xlog.Error(err)
		return
	}
	client.SetCharset("utf-8").SetSignType(alipay.RSA2).SetNotifyUrl(config.NotifyURL).SetReturnUrl(config.ReturnURL)
	outTradeNo := fmt.Sprintf("%s", "4562")
	bm := make(gopay.BodyMap)
	bm.Set("subject", "学生报名费用")
	funcName(bm, outTradeNo)
	bm.Set("total_amount", "66.00")
	bm.Set("product_code", config.ProductCode)
	payUrl, err := client.TradePagePay(context.Background(), bm)
	if err != nil {
		xlog.Error(err)
		return
	}
	fmt.Println(payUrl)
}
func funcName(bm gopay.BodyMap, outTradeNo string) gopay.BodyMap {
	return bm.Set("out_trade_no", outTradeNo)
}
